﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AB_SD_Entities;
using System.Data.SqlClient;
using System.Data;
using AB_SD_Commons.Helpers;

namespace AB_SD_DataAccess
{
    public static class AddressDAO
    {
        /// <summary>
        /// Search addresses by postcode, street or town
        /// </summary>
        /// <param name="strPostcode">postcode</param>
        /// <param name="strStreet">street</param>
        /// <param name="strTown">town name</param>
        /// <returns></returns>
        public static List<Address> Search(string strPostcode, string strStreet, string strTown)
        {
            List<Address> result = new List<Address>();
            
            string strQuery="select Address.Id, Address.Postcode, Address.Address, Address.TownId "
            + "from (Address join Town on Address.TownId = Town.Id) "
            + "where Address.Postcode like @postcode and Address.Address like @address and Town.Name like @town";
            
            SqlParameter[] sqlParam = new SqlParameter[3];

            sqlParam[0] = new SqlParameter("@postcode", SqlDbType.VarChar);
            if (strPostcode == null || strPostcode == "")
                sqlParam[0].Value = "%";
            else sqlParam[0].Value = "%"+strPostcode+"%";

            sqlParam[1] = new SqlParameter("@address", SqlDbType.VarChar);
            if (strStreet == null || strStreet == "")
                sqlParam[1].Value = "%";
            else sqlParam[1].Value = "%"+strStreet+"%";

            sqlParam[2] = new SqlParameter("@town", SqlDbType.VarChar);
            if (strTown == null || strTown == "")
                sqlParam[2].Value = "%";
            else sqlParam[2].Value = "%"+strTown+"%";

            DataTable dt = SqlHelper.ExecuteSelectQuery(strQuery, sqlParam);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Address address = new Address((int)dt.Rows[i]["Id"], dt.Rows[i]["Postcode"].ToString(), dt.Rows[i]["Address"].ToString(), (int)dt.Rows[i]["TownId"]);
                        result.Add(address);
                    }
                }
            }
            return result;
        }
    }
}
